<template>
  <div class="basic-info-form">
    <div class="form-header">
      <h3>{{ t('dashboard.profile.basicInfo.title') }}</h3>
      <p>{{ t('dashboard.profile.basicInfo.subtitle') }}</p>
    </div>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item :label="t('dashboard.profile.basicInfo.username')" prop="username">
            <el-input
              v-model="formData.username"
              disabled
              :placeholder="t('dashboard.profile.basicInfo.username_tip_1')"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
            <div class="form-tip">{{ t('dashboard.profile.basicInfo.username_tip_2') }}</div>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="t('dashboard.profile.basicInfo.realName')" prop="realName">
            <el-input
              v-model="formData.realName"
              :placeholder="t('dashboard.profile.basicInfo.realName_placeholder')"
              clearable
            >
              <template #prefix>
                <el-icon><UserFilled /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item :label="t('dashboard.profile.basicInfo.email')" prop="email">
            <el-input
              v-model="formData.email"
              :placeholder="t('dashboard.profile.basicInfo.email_placeholder')"
              clearable
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
            <div class="form-tip">{{ t('dashboard.profile.basicInfo.email_tip') }}</div>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="t('dashboard.profile.basicInfo.phone')" prop="phone">
            <el-input
              v-model="formData.phone"
              :placeholder="t('dashboard.profile.basicInfo.phone_placeholder')"
              clearable
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item :label="t('dashboard.profile.basicInfo.bio')" prop="bio">
            <el-input
              v-model="formData.bio"
              type="textarea"
              :rows="4"
              :placeholder="t('dashboard.profile.basicInfo.bio_placeholder')"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item :label="t('dashboard.profile.basicInfo.registeredAt')">
            <el-input
              :value="formatDate(authStore.user?.createdAt)"
              disabled
              :placeholder="t('dashboard.profile.basicInfo.registeredAt')"
            >
              <template #prefix>
                <el-icon><Calendar /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="t('dashboard.profile.basicInfo.updatedAt')">
            <el-input
              :value="formatDate(authStore.user?.updatedAt)"
              disabled
              :placeholder="t('dashboard.profile.basicInfo.updatedAt')"
            >
              <template #prefix>
                <el-icon><Clock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="form-actions">
        <el-button @click="handleReset">{{ t('dashboard.profile.basicInfo.reset') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ t('dashboard.profile.basicInfo.save') }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, UserFilled, Message, Phone, Calendar, Clock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const { t } = useI18n()

// 表单引用
const formRef = ref()
const loading = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  bio: ''
})

// 原始数据（用于重置）
const originalData = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  bio: ''
})

// 表单验证规则
const formRules = {
  realName: [
    { max: 50, message: t('dashboard.profile.basicInfo.rules.realName_max'), trigger: 'blur' }
  ],
  email: [
    { required: true, message: t('dashboard.profile.basicInfo.rules.email_required'), trigger: 'blur' },
    { type: 'email', message: t('dashboard.profile.basicInfo.rules.email_format'), trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: t('dashboard.profile.basicInfo.rules.phone_format'), trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: t('dashboard.profile.basicInfo.rules.bio_max'), trigger: 'blur' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (authStore.user) {
    const userData = {
      username: authStore.user.username || '',
      realName: authStore.user.realName || '',
      email: authStore.user.email || '',
      phone: '', // 后端暂时没有这个字段
      bio: '' // 后端暂时没有这个字段
    }
    
    Object.assign(formData, userData)
    Object.assign(originalData, userData)
  }
}

// 监听用户数据变化
watch(() => authStore.user, () => {
  initFormData()
}, { immediate: true })

// 格式化日期
const formatDate = (dateString?: string): string => {
  if (!dateString) return t('dashboard.profile.basicInfo.unknown')
  
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return t('dashboard.profile.basicInfo.format_error')
  }
}

// 检查是否有修改
const hasChanges = (): boolean => {
  return Object.keys(formData).some(key => {
    return formData[key as keyof typeof formData] !== originalData[key as keyof typeof originalData]
  })
}

// 重置表单
const handleReset = async () => {
  if (hasChanges()) {
    try {
      await ElMessageBox.confirm(
        t('dashboard.profile.basicInfo.messages.reset_confirm_text'),
        t('dashboard.profile.basicInfo.messages.reset_confirm_title'),
        {
          confirmButtonText: t('dashboard.profile.avatarDialog.confirm'),
          cancelButtonText: t('dashboard.profile.avatarDialog.cancel'),
          type: 'warning'
        }
      )
    } catch {
      return
    }
  }
  
  Object.assign(formData, originalData)
  formRef.value?.clearValidate()
  ElMessage.success(t('dashboard.profile.basicInfo.messages.reset_success'))
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    if (!hasChanges()) {
      ElMessage.info(t('dashboard.profile.basicInfo.messages.no_change'))
      return
    }
    
    loading.value = true
    
    // TODO: 调用更新用户信息的API
    await new Promise(resolve => setTimeout(resolve, 1500)) // 模拟API调用
    
    // 更新原始数据
    Object.assign(originalData, formData)
    
    // 更新store中的用户信息
    if (authStore.user) {
      authStore.user.realName = formData.realName
      authStore.user.email = formData.email
    }
    
    ElMessage.success(t('dashboard.profile.basicInfo.messages.update_success'))
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('dashboard.profile.basicInfo.messages.update_fail'))
      console.error('更新失败:', error)
    }
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(() => {
  initFormData()
})
</script>

<style lang="scss" scoped>
.basic-info-form {
  .form-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color-light);

    h3 {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
      transition: color 0.3s ease;
    }

    p {
      font-size: 14px;
      color: var(--text-color-secondary);
      margin: 0;
      transition: color 0.3s ease;
    }
  }

  .form-tip {
    font-size: 12px;
    color: var(--text-color-secondary);
    margin-top: 4px;
    line-height: 1.4;
    transition: color 0.3s ease;
  }

  .form-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color-light);
    text-align: right;

    .el-button {
      margin-left: 12px;
    }
  }

  // Element Plus 组件样式覆盖
  :deep(.el-form-item__label) {
    color: var(--text-color-primary);
    font-weight: 500;
    transition: color 0.3s ease;
  }

  :deep(.el-input__wrapper) {
    background-color: var(--bg-color-tertiary);
    border: 1px solid var(--border-color-light);
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--theme-primary);
    }

    &.is-focus {
      border-color: var(--theme-primary);
      box-shadow: 0 0 0 2px var(--theme-primary-shadow);
    }
  }

  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: var(--bg-color-secondary);
    border-color: var(--border-color-light);
  }

  :deep(.el-textarea__inner) {
    background-color: var(--bg-color-tertiary);
    border: 1px solid var(--border-color-light);
    color: var(--text-color-primary);
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--theme-primary);
    }

    &:focus {
      border-color: var(--theme-primary);
      box-shadow: 0 0 0 2px var(--theme-primary-shadow);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .basic-info-form {
    :deep(.el-col) {
      width: 100% !important;
      flex: 0 0 100% !important;
      max-width: 100% !important;
    }

    .form-actions {
      text-align: center;

      .el-button {
        margin: 0 6px;
      }
    }
  }
}
</style>
